<template>
  <div v-if="show" class="leaderboard-dialog">
    <div class="dialog-content">
      <h3>排行榜</h3>
      
      <div class="leaderboard-filters">
        <select v-model="timeRange">
          <option value="all">所有时间</option>
          <option value="month">本月</option>
          <option value="week">本周</option>
          <option value="day">今日</option>
        </select>
        
        <input 
          type="text" 
          v-model="searchQuery"
          placeholder="搜索玩家..."
        >
      </div>

      <div class="leaderboard-table">
        <table>
          <thead>
            <tr>
              <th>排名</th>
              <th>玩家</th>
              <th>等级分</th>
              <th>胜率</th>
              <th>连胜</th>
              <th>最高分</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(player, index) in filteredPlayers" 
              :key="player.id"
              :class="{ 'current-player': player.id === currentPlayerId }"
            >
              <td>{{ index + 1 }}</td>
              <td>{{ player.username }}</td>
              <td>
                {{ player.rating }}
                <span 
                  class="rating-change"
                  :class="getRatingChangeClass(player.id)"
                >
                  {{ formatRatingChange(player.id) }}
                </span>
              </td>
              <td>{{ getWinRate(player).toFixed(1) }}%</td>
              <td>{{ player.winStreak }}</td>
              <td>{{ player.bestRating }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="player-stats" v-if="currentPlayer">
        <h4>你的统计</h4>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">排名</div>
            <div class="stat-value">{{ getPlayerRank(currentPlayerId) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">胜/负/平</div>
            <div class="stat-value">
              {{ currentPlayer.wins }}/{{ currentPlayer.losses }}/{{ currentPlayer.draws }}
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最高连胜</div>
            <div class="stat-value">{{ currentPlayer.winStreak }}</div>
          </div>
        </div>

        <div class="rating-history">
          <canvas ref="ratingChart"></canvas>
        </div>
      </div>

      <div class="dialog-buttons">
        <button @click="$emit('close')">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRankingSystem } from '../composables/useRankingSystem'
import Chart from 'chart.js/auto'
import type { PlayerRank } from '../types/ranking'

const props = defineProps<{
  show: boolean
  currentPlayerId: string
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

const {
  leaderboard,
  getPlayerRank,
  getPlayerHistory,
  getWinRate
} = useRankingSystem()

const timeRange = ref<'all' | 'month' | 'week' | 'day'>('all')
const searchQuery = ref('')
const ratingChart = ref<HTMLCanvasElement | null>(null)

const currentPlayer = computed(() => 
  leaderboard.value.find(p => p.id === props.currentPlayerId)
)

const filteredPlayers = computed(() => {
  let players = leaderboard.value

  if (searchQuery.value) {
    players = players.filter(p => 
      p.username.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  if (timeRange.value !== 'all') {
    const now = new Date()
    const timeLimit = new Date()
    
    switch (timeRange.value) {
      case 'month':
        timeLimit.setMonth(now.getMonth() - 1)
        break
      case 'week':
        timeLimit.setDate(now.getDate() - 7)
        break
      case 'day':
        timeLimit.setDate(now.getDate() - 1)
        break
    }

    players = players.filter(p => p.lastActive >= timeLimit)
  }

  return players
})

const getRatingChangeClass = (playerId: string): string => {
  const history = getPlayerHistory(playerId)
  if (!history.length) return ''
  const lastChange = history[history.length - 1].change
  return lastChange > 0 ? 'positive' : lastChange < 0 ? 'negative' : ''
}

const formatRatingChange = (playerId: string): string => {
  const history = getPlayerHistory(playerId)
  if (!history.length) return ''
  const change = history[history.length - 1].change
  return change > 0 ? `+${change}` : `${change}`
}

const createRatingChart = () => {
  if (!ratingChart.value || !currentPlayer.value) return

  const history = getPlayerHistory(props.currentPlayerId)
  const ctx = ratingChart.value.getContext('2d')
  if (!ctx) return

  new Chart(ctx, {
    type: 'line',
    data: {
      labels: history.map((_, i) => i + 1),
      datasets: [{
        label: '等级分变化',
        data: history.map(h => h.newRating),
        borderColor: '#4CAF50',
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: false
        }
      }
    }
  })
}

watch(() => props.show, (newVal) => {
  if (newVal) {
    setTimeout(createRatingChart, 0)
  }
})

onMounted(() => {
  if (props.show) {
    createRatingChart()
  }
})
</script>

<style scoped>
/* ... 样式代码 ... */
</style> 